package com.king.common.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.king.common.exception.AssertHelper;

/**
 * 验证实体是否合法工具类
 * @author yy-team
 * @date 2018年8月8日
 */
public class ValidatorUtil {

	Logger logger = LoggerFactory.getLogger(ValidatorUtil.class);

	private static Validator validator = ((HibernateValidatorConfiguration) Validation.byProvider(HibernateValidator.class).configure()).failFast(true)
			.buildValidatorFactory().getValidator();

	/**
	 * 实体校验
	 * 
	 * @param obj
	 * @throws CommonException
	 */
	public static <T> void validate(T obj) throws Exception {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, new Class[0]);
		if (constraintViolations.size() > 0) {
			ConstraintViolation<T> validateInfo = (ConstraintViolation<T>) constraintViolations.iterator().next();
			// 获取那个字段
			String fieldName = validateInfo.getPropertyPath().toString();
			// 获取那个实体
			Class<T> c = validateInfo.getRootBeanClass();
			String msg = validateInfo.getMessage();
			if (StringUtils.isNotEmpty(fieldName)) {

				// 获取值
				msg = MetaDataUtil.getValue(c, fieldName) + ":" + validateInfo.getMessage();
			}
			AssertHelper.getInstance().throwException(msg);
		}
	}

}